package com.cjzuji.rental.curl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionExample {

    public static String sendCurlRequest(String url, String method, String body) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法
            con.setRequestMethod(method);
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("accesstoken", "5PE8JA8C3DZ5F1C8IA2AE8G73U33HFATC860DTDDXDB048A8");
            con.setRequestProperty("authorization", "5PE8JA8C3DZ5F1C8IA2AE8G73U33HFATC860DTDDXDB048A8");

            // 发送数据到服务器（例如，如果是POST请求）
            if (body != null && !body.isEmpty()) {
                con.setDoOutput(true);
                try (OutputStream os = con.getOutputStream()) {
                    os.write(body.getBytes());
                    os.flush();
                }
            }

            // 获取响应状态码
            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            // 读取响应内容
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}